const { T_user } = require('../models/t_user')//导入个人模型
const { T_academy } = require('../models/T_academy')//导入学院模型
const { T_subject_and_academy } = require('../models/T_subject_and_academy')//导入科目与学院模型
const { T_user_and_academy } = require('../models/T_user_and_academy')//导入用户与学院模型
const { T_subjects } = require('../models/t_exam_subjects')//导入学科模型
const { T_user_and_subject } = require('../models/T_user_and_subject')
const { T_class } = require('../models/t_class')
const { T_user_and_a_c_s } = require('../models/t_user_and_a_c_s')
const { T_grade } = require('../models/t_grade')

//通过用户来返回对应学院和科目（名称）
exports.getAcacademyAndSubjectByUser = async (req, res) => {
  try {
    const user_id = req.params.user_id;

    // 查询用户对应的学院信息
    const userAndAcademy = await T_user_and_academy.findOne({
      where: {
        user_id: user_id
      }
    });

    if (!userAndAcademy) {
      return res.status(404).json({ msg: '该用户暂时没有对应学院' });
    }

    //提取学院名称
    const academy_ID = userAndAcademy.academy_id
    const academy = await T_academy.findByPk(academy_ID)
    const academy_name = academy.academy_name

    // 查询学院对应的科目信息
    const subjectsAndAcademy = await T_subject_and_academy.findAll({
      where: { academy_id: academy_ID }, // 根据学院 ID 查询
    });


    if (subjectsAndAcademy.length === 0) {
      res.status(404).json({ msg: '未找到与该学院相关的科目信息' });
      return;
    }

    //提取科目id
    const subid = subjectsAndAcademy.map(T_subject_and_academy => T_subject_and_academy.subject_id)

    const subjects = await T_subjects.findAll({
      attributes: ['subject'], // 只选择名称字段
      where: {
        id: subid,
      },
    });


    // 返回学院和科目信息
    res.json({
      'code': 200,
      'msg': "查询成功",
      'data': {
        'academy_name': academy_name,
        'subject': subjects
      }
    });
  } catch (error) {
    console.error('Error querying database:', error); // 如果出错，打印错误信息
    res.status(500).json({
      'msg': error
    }); // 返回 500 错误
  }
};

//建立用户与学院的绑定关系(通过邀请码)
exports.createt_useAcademy = async (req, res) => {
  const body = req.body;
  try {

    const academy = await T_academy.findOne({
      where: {
        invitation_code: body.invitation_code
      }
    })

    if (!academy) {
      res.json({
        'code': 203,
        'msg': '请输入正确的邀请码'
      });
      return;
    }

    const academyid = academy.id


    const user_and_academy = await T_user_and_academy.create({
      user_id: body.user_id,
      academy_id: academyid,
    });

    res.json({
      "code": 200,
      "msg": `欢迎加入${academy.academy_name}`,
      "data": {
        'data': user_and_academy
      },
    });
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message,
    });
  }
};

//通过用户来返回对应学院和科目（id）
exports.getAcacademyAndSubjectidByUser = async (req, res) => {
  try {
    const user_id = req.params.user_id;

    // 查询用户对应的学院信息
    const userAndAcademy = await T_user_and_academy.findOne({
      where: {
        user_id: user_id
      }
    });

    if (!userAndAcademy) {
      res.json({
        'code': 203,
        'msg': '该用户暂时没有对应学院'
      });
      return
    }

    //提取学院名称
    const academy_ID = userAndAcademy.academy_id
    const academy = await T_academy.findByPk(academy_ID)
    const academy_name = academy.academy_name

    // 查询学院对应的科目信息
    const subjectsAndAcademy = await T_subject_and_academy.findAll({
      where: { academy_id: academy_ID }, // 根据学院 ID 查询
    });


    if (subjectsAndAcademy.length === 0) {
      res.json({
        'code': 203,
        'msg': '未找到与该学院相关的科目信息'
      });
      return;
    }

    //提取科目id
    const subid = subjectsAndAcademy.map(T_subject_and_academy => T_subject_and_academy.subject_id)

    // 返回学院和科目信息
    res.json({
      'code': 200,
      'msg': "查询成功",
      'data': {
        'academy_name': academy_name,
        'subjectid': subid
      }
    });
  } catch (error) {
    console.error('Error querying database:', error); // 如果出错，打印错误信息
    res.status(500).json({
      'msg': error
    }); // 返回 500 错误
  }
};

//绑定用户与所教学科(用户id和科目id（数组形式）传给我)
exports.MakeUseAndSubject = async (req, res) => {
  const { use_id, subject_id } = req.body;
  try {
    const createdUserSubjects = [];

    for (const subjectId of subject_id) {
      const UseAndSubject = await T_user_and_subject.create({
        use_id: use_id,
        subject_id: subjectId
      });
      createdUserSubjects.push(UseAndSubject);
    }

    res.json({
      "code": 200,
      "msg": '绑定成功',
      "data": createdUserSubjects
    });
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message
    });
  }
}

//通过学院id来回去科目id和名称
exports.getSubjectsByAcademy = async (req, res) => {
  const academy_id = req.params.academy_id;
  try {
    // 0. 查询学院名称
    console.log(academy_id);
    const academy = await T_academy.findOne({ where: { id: academy_id } });

    if (!academy) {
      return res.status(404).json({
        'code': 404,
        'msg': '找不到该学院信息'
      });
    }

    // 1. 查询属于该学院的所有科目关联数据
    const subjectsAndAcademies = await T_subject_and_academy.findAll({
      where: {
        academy_id: academy_id
      }
    });

    if (!subjectsAndAcademies || subjectsAndAcademies.length === 0) {
      return res.json({
        'code': 203,
        'msg': '该学院没有相关科目数据'
      });
    }

    // 2. 提取科目关联数据中的科目 ID
    const subjectIds = subjectsAndAcademies.map(item => item.subject_id);

    // 3. 查询这些科目的详细信息
    const subjects = await T_subjects.findAll({
      where: {
        id: subjectIds
      }
    });

    if (!subjects || subjects.length === 0) {
      return res.json({
        'code': 203,
        'msg': '找不到相关科目信息'
      });
    }

    // 4. 构建科目信息对象数组
    const result = subjects.map(subject => ({
      id: subject.id,
      subject: subject.subject
    }));

    res.json({
      'code': 200,
      'data': {
        'academyName': academy.academy_name,
        'subjectidAndName': result
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      msg: error.message
    });
  }
};

//通过用户id来返回所教科目的所有信息
exports.getALLSubjectsByUse = async (req, res) => {
  const user_id = req.params.user_id;
  try {

    // 第一步：查询用户对应的全部数据
    const userAcsData = await T_user_and_a_c_s.findAll({
      where: { user_id: user_id }
    });

    // 第二步：处理每条数据，查询对应的名称
    const userDataWithName = await Promise.all(userAcsData.map(async (row) => {
      // 查询对应的学院名称
      const academy = await T_academy.findByPk(row.academy_id);
      const academyName = academy ? academy.academy_name : null;

      // 查询对应的班级名称
      const classObj = await T_class.findByPk(row.class_id);
      const className = classObj ? classObj.class_name : null;

      // 查询对应的科目名称
      const subject = await T_subjects.findByPk(row.subject_id);
      const subjectName = subject ? subject.subject : null;

      //查询对应学年
      const grade = await T_grade.findByPk(row.grade_id);
      const gradeName = grade ? grade.grade_name : null;

      return {
        user_and_acs_id: row.id,
        grade_id: row.grade_id,
        grade_name: gradeName,
        academy_id: row.academy_id,
        academy_name: academyName,
        class_id: row.class_id,
        class_name: className,
        subject_id: row.subject_id,
        subject_name: subjectName
      };
    }));

    // 第三步：返回处理后的数据给前端
    res.json({
      'code': 200,
      'msg': '查询成功',
      'data': userDataWithName
    });
  } catch (error) {
    console.error('查询失败:', error);
    res.status(500).json({ error: '查询失败' });
  }
};